package servlets;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.CandidateService;
import service.InterviewService;
import service.UserService;
import entityJPA.Interview;
import entityJPA.User;

/**
 * Servlet implementation class InterviewServlet
 */
@WebServlet("/InterviewServlet")
public class InterviewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	private UserService userService;
	// private HttpSession h;

	@EJB
	private InterviewService interviewService;
	@EJB
	private CandidateService candidateService;

	private int idCandidate;

	public InterviewServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		idCandidate = Integer.parseInt(request.getParameter("idCandidate"));
		HttpSession h = request.getSession();
		try {
			if (candidateService.getCandidateById(idCandidate) != null) {
				doPost(request, response);
			} else {

				h.setAttribute("exceptionMessage",
						"This candidate does not exist in the database.");
				response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
			}
		} catch (Exception e) {
			h.setAttribute("exceptionMessage",
					"This position does not exist in the database.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession h = request.getSession();
		if (h.getAttribute("newUserList") == null)
			h.setAttribute("newUserList", new Vector<User>());
		try {
			h.setAttribute("userInterviewList", userService.getUserFindAll());

			h.setAttribute("candidateInterviews",
					interviewService.getCandidateInterviews(idCandidate));

			if (request.getParameter("addUserInterview") != null) {
				addUserInterview(request, response);
			} else if (request.getParameter("addInterview") != null) {
				addInterview(request, response);
			} else if (request.getParameter("deleteUser") != null) {
				removeUserFromList(request, response);
			}
			getServletContext()
					.getRequestDispatcher("/candidate/interview.jsp").forward(
							request, response);
		} catch (Exception e) {
			h.setAttribute("exceptionMessage",
					"An error occured while processing your request.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}

	}

	@SuppressWarnings("unchecked")
	private void addUserInterview(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession h = request.getSession();

		Vector<User> newUserList = (Vector<User>) h.getAttribute("newUserList");

		if (!newUserList.contains(userService.getUserById(Integer
				.parseInt(request.getParameter("userInterview"))))) {
			newUserList.add(userService.getUserById(Integer.parseInt(request
					.getParameter("userInterview"))));
			h.setAttribute("newUserList", newUserList);
		}

	}

	@SuppressWarnings("unchecked")
	private void addInterview(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		HttpSession h = request.getSession();
		Vector<User> userList = (Vector<User>) h.getAttribute("newUserList");
		if (userList != null) {
			Interview interview = new Interview();
			interview.setUsers(userList);
			Date date = null;
			try {
				String dateInterview = request.getParameter("dateInterview");
				String userAgent = request.getHeader("User-Agent");
				String user = userAgent.toLowerCase();
				if (user.contains("chrome")) {
					date = new SimpleDateFormat("yyyy-MM-dd")
							.parse(dateInterview);
				} else if (user.contains("firefox")) {
					date = new SimpleDateFormat("MM/dd/yyyy")
							.parse(dateInterview);
				}

				interview.setDate(date);
				interview.setCandidate(candidateService
						.getCandidateById(idCandidate));
				interviewService.addInterview(interview);
				h.setAttribute("newUserList", new Vector<User>());
				h.setAttribute("candidateInterviews",
						interviewService.getCandidateInterviews(idCandidate));

			} catch (ParseException e) {
				h.setAttribute("exceptionMessage",
						"Could not get the date you have picked.");
				response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
			}
		}

	}

	@SuppressWarnings("unchecked")
	private void removeUserFromList(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession h = request.getSession();
		String deletedUserId = request.getParameter("deletedUserId");
		deletedUserId = deletedUserId.replaceAll(" ", "");
		int idUser = Integer.parseInt(deletedUserId);
		User u = userService.getUserById(idUser);
		Vector<User> newUserList = (Vector<User>) h.getAttribute("newUserList");
		newUserList.remove(u);
		h.setAttribute("newUserList", newUserList);

	}
}
